﻿import React, { useEffect, useState, useMemo, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { useSelector, useDispatch } from 'react-redux';
import { useTranslation } from 'react-i18next';
import {
  Box,
  Container,
  Grid,
  Typography,
  Card,
  CardContent,
  CardActions,
  Button,
  Chip,
  LinearProgress,
  Divider,
  Paper,
  List,
  ListItem,
  ListItemText,
  ListItemIcon,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogContentText,
  DialogActions,
  CircularProgress,
  Alert
} from '@mui/material';
import {
  Lock as LockIcon,
  LockOpen as UnlockIcon,
  ArrowUpward as LevelUpIcon,
  CheckCircle as CompletedIcon,
  Star as StarIcon,
  Restore as RestoreIcon,
  Refresh as RefreshIcon,
  CheckCircle
} from '@mui/icons-material';
import { RootState } from '../redux/store';
import { AppDispatch } from '../redux/store';
import { getOverallProgress, getUserStatistics, levelUp, selectPattern, generateChallenges, resetProgress, completeAllPatterns, resetToBeginnerLevel } from '../redux/slices/progressSlice';
import { getPatterns } from '../redux/slices/patternSlice';
import { addAlert } from '../redux/slices/uiSlice';

// 定义扩展的进度接口，添加新属性
interface ExtendedOverallProgress {
  currentLevel: 'beginner' | 'intermediate' | 'advanced';
  nextLevel: 'intermediate' | 'advanced' | null;
  completedPatterns: {
    beginner: any[];
    intermediate: any[];
    advanced: any[];
  } | string[]; // 兼容数组格式
  level?: string; // 新的level属性
}

// 定义扩展的模式接口，添加新属性
interface ExtendedPattern {
  _id: string;
  name: string;
  category: string;
  level?: string; // 新的level属性
  description?: string;
}

const Dashboard: React.FC = () => {
  const dispatch = useDispatch<AppDispatch>();
  const navigate = useNavigate();
  const { t, i18n } = useTranslation();
  const { user } = useSelector((state: RootState) => state.auth);
  const { overallProgress, statistics, loading, error } = useSelector((state: RootState) => state.progress);
  const { patterns } = useSelector((state: RootState) => state.patterns);
  const uiLoading = useSelector((state: RootState) => state.ui.loading);
  
  const [upgradeDialogOpen, setUpgradeDialogOpen] = useState(false);
  const [generationProgress, setGenerationProgress] = useState(0);
  const [generationStatus, setGenerationStatus] = useState('');
  const [newLevel, setNewLevel] = useState<string | null>(null);
  const [resetConfirmOpen, setResetConfirmOpen] = useState(false);
  const [dataError, setDataError] = useState<string | null>(null);
  const [debugInfo, setDebugInfo] = useState<Record<string, any>>({});
  const [forcedRender, setForcedRender] = useState(false);
  const [loadingTimeout, setLoadingTimeout] = useState(false);
  const [initialLoadComplete, setInitialLoadComplete] = useState(false);

  // 使用useMemo对数据提前处理，减少重复计算
  const processedData = useMemo(() => {
    try {
      // 首次加载检查
      if (!overallProgress && !patterns) {
        console.log('数据未加载，返回默认值');
        return {
          userLevel: 'beginner',
          nextUserLevel: 'intermediate',
          completedPatternsArray: [],
          currentLevelPatterns: [],
          completedPatterns: []
        };
      }

      // 安全地获取数据
      const safeOverallProgress = overallProgress || {
        currentLevel: 'beginner',
        nextLevel: 'intermediate',
        completedPatterns: []
      };
      
      const safePatterns = Array.isArray(patterns) ? patterns : [];
      
      console.log('处理数据...', { 
        overallProgress: safeOverallProgress,
        patternsCount: safePatterns.length
      });
      
      // 确保用户级别标准化(小写)
      let userLevel = 'beginner';
      if (typeof safeOverallProgress.currentLevel === 'string') {
        userLevel = safeOverallProgress.currentLevel.toLowerCase();
      } else if (typeof (safeOverallProgress as any).level === 'string') {
        userLevel = (safeOverallProgress as any).level.toLowerCase();
      }
      
      // 确保下一个级别标准化(小写)
      let nextUserLevel = 'intermediate';
      if (typeof safeOverallProgress.nextLevel === 'string') {
        nextUserLevel = safeOverallProgress.nextLevel.toLowerCase();
      } else if (userLevel === 'intermediate') {
        nextUserLevel = 'advanced';
      } else if (userLevel === 'advanced') {
        nextUserLevel = '';  // 使用空字符串替代null
      }
      
      // 统一解析已完成模式列表
      let completedPatternsArray: string[] = [];
      if (safeOverallProgress.completedPatterns) {
        if (Array.isArray(safeOverallProgress.completedPatterns)) {
          completedPatternsArray = safeOverallProgress.completedPatterns;
        } else if (typeof safeOverallProgress.completedPatterns === 'object') {
          const levelData = safeOverallProgress.completedPatterns[userLevel as keyof typeof safeOverallProgress.completedPatterns];
          if (levelData && Array.isArray(levelData)) {
            completedPatternsArray = levelData.map((p: any) => {
              return typeof p === 'string' ? p : (p && p._id ? p._id : '');
            }).filter(Boolean);
          }
        }
      }
      
      // 过滤当前级别的模式
      const currentLevelPatterns = safePatterns.filter(pattern => {
        if (!pattern) return false;
        
        // 检查模式级别 - 优先使用pattern.level，否则所有模式都可见
        if ((pattern as ExtendedPattern).level) {
          const level = (pattern as ExtendedPattern).level;
          return level && level.toLowerCase() === userLevel;
        }
        return true;
      });
      
      // 过滤已完成的模式
      const completedPatterns = completedPatternsArray.length > 0
        ? safePatterns.filter(pattern => {
            return pattern && completedPatternsArray.includes(pattern._id);
          })
        : [];
      
      console.log('数据处理完成', {
        userLevel,
        nextUserLevel,
        completedCount: completedPatterns.length,
        availableCount: currentLevelPatterns.length,
        completedIds: completedPatternsArray
      });
      
      return {
        userLevel,
        nextUserLevel,
        completedPatternsArray,
        currentLevelPatterns,
        completedPatterns
      };
    } catch (err) {
      console.error('数据处理异常:', err);
      setDataError('数据处理出错，请刷新页面重试');
      
      // 返回默认值以防止UI崩溃
      return {
        userLevel: 'beginner',
        nextUserLevel: 'intermediate',
        completedPatternsArray: [],
        currentLevelPatterns: [],
        completedPatterns: []
      };
    }
  }, [overallProgress, patterns, forcedRender]); // 添加forcedRender依赖

  // 增强的useEffect，添加更多调试信息
  useEffect(() => {
    console.log('Dashboard组件初始化');
    
    // 设置加载超时处理
    const timeoutId = setTimeout(() => {
      console.log('加载超时，强制渲染');
      setLoadingTimeout(true);
    }, 5000);
    
    try {
      // 获取进度信息
      dispatch(getOverallProgress())
        .unwrap()
        .then(result => {
          console.log('进度数据加载成功:', result);
          setDebugInfo(prevInfo => ({
            ...prevInfo,
            overallProgress: result
          }));
        })
        .catch(err => {
          console.error('加载进度数据失败:', err);
          setDataError('加载进度数据失败，请刷新页面重试');
        });
      
      // 获取统计信息
      dispatch(getUserStatistics())
        .unwrap()
        .then(result => {
          console.log('统计数据加载成功:', result);
          setDebugInfo(prevInfo => ({
            ...prevInfo,
            statistics: result
          }));
        })
        .catch(err => {
          console.error('加载统计数据失败:', err);
        });
      
      // 获取模式列表
      dispatch(getPatterns())
        .unwrap()
        .then(result => {
          console.log('模式数据加载成功:', result);
          setDebugInfo(prevInfo => ({
            ...prevInfo,
            patterns: result
          }));
          
          // 所有数据都已加载
          setInitialLoadComplete(true);
        })
        .catch(err => {
          console.error('加载模式数据失败:', err);
          setDataError('加载模式数据失败，请刷新页面重试');
        });

      return () => clearTimeout(timeoutId);
    } catch (err) {
      console.error('Dashboard初始化异常:', err);
      setDataError('初始化失败，请刷新页面重试');
      clearTimeout(timeoutId);
    }
  }, [dispatch]);

  // 刷新数据的处理函数
  const handleRefreshData = useCallback(() => {
    console.log('手动刷新数据');
    setDataError(null);
    
    // 获取进度信息
    dispatch(getOverallProgress())
      .unwrap()
      .then(result => {
        console.log('刷新: 进度数据加载成功:', result);
        // 强制重新渲染
        setForcedRender(prev => !prev);
      })
      .catch(err => {
        console.error('刷新: 加载进度数据失败:', err);
        setDataError('刷新数据失败，请重试');
      });
    
    // 获取模式列表
    dispatch(getPatterns())
      .unwrap()
      .then(result => {
        console.log('刷新: 模式数据加载成功:', result);
      })
      .catch(err => {
        console.error('刷新: 加载模式数据失败:', err);
      });
  }, [dispatch]);

  // 完成当前等级所有模式的处理函数
  const handleCompleteAllPatterns = useCallback(() => {
    if (!processedData.userLevel) return;
    
    console.log('完成当前等级所有模式');
    
    dispatch(completeAllPatterns())
      .unwrap()
      .then(() => {
        dispatch(addAlert({
          type: 'success',
          message: t('dashboard.completeAllSuccess')
        }));
        
        // 刷新进度数据
        dispatch(getOverallProgress());
      })
      .catch((error: string) => {
        dispatch(addAlert({
          type: 'error',
          message: error
        }));
      });
  }, [dispatch, t, processedData.userLevel]);

  const handlePatternSelect = (patternId: string) => {
    dispatch(selectPattern(patternId))
      .unwrap()
      .then(() => {
        navigate(`/patterns/${patternId}`);
      })
      .catch((error: string) => {
        dispatch(addAlert({
          type: 'error',
          message: error
        }));
      });
  };

  const handleLevelUp = () => {
    dispatch(levelUp())
      .unwrap()
      .then((result: any) => {
        // 显示升级对话框
        setNewLevel(result.level);
        setUpgradeDialogOpen(true);
        setGenerationStatus(t('dashboard.upgrade.starting'));
        
        // 获取最新的进度信息
        dispatch(getOverallProgress());
        
        // 确保patterns已加载
        if (!patterns || patterns.length === 0) {
          console.error('Patterns not loaded');
          setGenerationStatus(t('dashboard.upgrade.error'));
          dispatch(addAlert({
            type: 'error',
            message: t('dashboard.patternsNotLoaded')
          }));
          
          // 关闭对话框
          setTimeout(() => {
            setUpgradeDialogOpen(false);
            setGenerationProgress(0);
          }, 2000);
          return;
        }
        
        // 按类别分组模式
        const creationalPatterns = patterns.filter(p => p && p.category === 'Creational').map(p => p._id);
        const structuralPatterns = patterns.filter(p => p && p.category === 'Structural').map(p => p._id);
        const behavioralPatterns = patterns.filter(p => p && p.category === 'Behavioral').map(p => p._id);
        
        // 首先生成创建型和结构型模式的挑战
        setGenerationStatus(t('dashboard.upgrade.creationalAndStructural'));
        setGenerationProgress(20);
        
        const combinedPatterns = [...creationalPatterns, ...structuralPatterns];
        
        dispatch(generateChallenges({
          patternIds: combinedPatterns,
          patternType: result.level
        }))
          .unwrap()
          .then(() => {
            // 然后生成行为型模式的挑战
            setGenerationStatus(t('dashboard.upgrade.behavioral'));
            setGenerationProgress(60);
            
            return dispatch(generateChallenges({
              patternIds: behavioralPatterns,
              patternType: result.level
            })).unwrap();
          })
          .then(() => {
            setGenerationStatus(t('dashboard.upgrade.completed'));
            setGenerationProgress(100);
            
            // 显示成功消息
            dispatch(addAlert({
              type: 'success',
              message: t('dashboard.upgrade.success', { level: result.level })
            }));
            
            // 关闭对话框
            setTimeout(() => {
              setUpgradeDialogOpen(false);
              setGenerationProgress(0);
              
              // 刷新页面以更新UI
              window.location.reload();
            }, 2000);
          })
          .catch((error: string) => {
            console.error('生成挑战失败:', error);
            
            setGenerationStatus(t('dashboard.upgrade.partialSuccess'));
            setGenerationProgress(100);
            
            dispatch(addAlert({
              type: 'warning',
              message: t('dashboard.upgrade.partialSuccess')
            }));
            
            // 关闭对话框
            setTimeout(() => {
              setUpgradeDialogOpen(false);
              setGenerationProgress(0);
              
              // 刷新页面以更新UI
              window.location.reload();
            }, 2000);
          });
      })
      .catch((error: string) => {
        console.error('升级失败:', error);
        
        dispatch(addAlert({
          type: 'error',
          message: error
        }));
      });
  };

  // 重置当前等级的进度
  const handleResetProgress = () => {
    if (!processedData.userLevel) return;
    
    dispatch(resetProgress())
      .unwrap()
      .then(() => {
        dispatch(addAlert({
          type: 'success',
          message: t('dashboard.resetSuccess')
        }));
        
        // 刷新进度数据
        dispatch(getOverallProgress());
      })
      .catch((error: string) => {
        dispatch(addAlert({
          type: 'error',
          message: error
        }));
      });
  };

  // 重置为初学者
  const handleResetToBeginnerLevel = () => {
    setResetConfirmOpen(true);
  };

  // 确认重置为初学者
  const confirmResetToBeginner = () => {
    console.log('执行重置操作');
    
    dispatch(resetToBeginnerLevel())
      .unwrap()
      .then((result) => {
        console.log('重置成功，结果:', result);
        
        // 显示成功消息
        dispatch(addAlert({
          type: 'success',
          message: t('dashboard.resetToBeginnerSuccess')
        }));
        
        // 刷新进度数据
        dispatch(getOverallProgress())
          .unwrap()
          .then(result => {
            console.log('重置后获取新进度成功:', result);
          })
          .catch(err => {
            console.error('重置后获取新进度失败:', err);
          });
        
        setResetConfirmOpen(false);
      })
      .catch((error: string) => {
        console.error('重置失败:', error);
        
        dispatch(addAlert({
          type: 'error',
          message: error
        }));
        setResetConfirmOpen(false);
      });
  };

  // 关闭重置确认对话框
  const handleCloseResetConfirm = () => {
    setResetConfirmOpen(false);
  };
  
  // 关闭错误提示
  const handleCloseError = () => {
    setDataError(null);
  };

  const getLevelTranslation = (level: string) => {
    return t(`challenge.levels.${level}`);
  };

  // 从处理后的数据中提取值
  const {
    userLevel,
    nextUserLevel,
    completedPatternsArray,
    currentLevelPatterns,
    completedPatterns
  } = processedData;

  // 调试信息
  console.log('Redux状态:', { loading, uiLoading, error, forcedRender, loadingTimeout });
  console.log('安全处理后数据:', { userLevel, nextUserLevel, completedPatterns: completedPatterns.length });
  console.log('原始数据:', { overallProgress, patterns, initialLoadComplete });

  // 显示加载状态 - 如果5秒内没有加载完成，则显示刷新按钮
  if ((!initialLoadComplete && (loading || uiLoading)) && !loadingTimeout) {
    console.log('正在加载中...', { loading, overallProgress: !!overallProgress, uiLoading, loadingTimeout });
    
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh', flexDirection: 'column' }}>
        <CircularProgress sx={{ mb: 2 }} />
        <Typography variant="body1" color="text.secondary">
          {t('common.loading')}
        </Typography>
        <Button 
          variant="text"
          color="primary"
          sx={{ mt: 2 }}
          onClick={() => window.location.reload()}
        >
          {t('common.refresh')}
        </Button>
      </Box>
    );
  }

  // 如果有错误，显示错误信息
  if (error || dataError) {
    console.error('发生错误:', error || dataError);
    return (
      <Box sx={{ p: 3 }}>
        <Alert severity="error" onClose={handleCloseError}>
          {error || dataError}
        </Alert>
        <Box sx={{ mt: 2, textAlign: 'center' }}>
          <Button 
            variant="contained" 
            color="primary"
            onClick={() => window.location.reload()}
          >
            {t('common.refresh')}
          </Button>
        </Box>
      </Box>
    );
  }

  // 仪表盘内容
  return (
    <Container maxWidth="lg" sx={{ mt: 4, mb: 4 }}>
      {/* 顶部欢迎区域 */}
      <Box sx={{ mb: 4, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div>
          <Typography variant="h4" gutterBottom>
            {t('dashboard.welcome')}
          </Typography>
          <Typography variant="body1" color="text.secondary">
            {t('dashboard.description')}
          </Typography>
        </div>
        <Button 
          variant="outlined" 
          color="primary" 
          startIcon={<RefreshIcon />}
          onClick={handleRefreshData}
        >
          {t('common.refresh')}
        </Button>
      </Box>

      <Grid container spacing={4}>
        {/* 进度信息卡片 */}
        <Grid item xs={12} md={6}>
          <Card>
            <CardContent>
              <Typography variant="h6" gutterBottom>
                {t('dashboard.progress.title')}
              </Typography>
              
              <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
                <Chip 
                  label={`${t('dashboard.progress.level')}: ${getLevelTranslation(userLevel)}`}
                  color="primary" 
                  variant="outlined" 
                />
                
                {nextUserLevel && (
                  <Button
                    variant="contained"
                    color="primary"
                    size="small"
                    startIcon={<LevelUpIcon />}
                    onClick={handleLevelUp}
                  >
                    {t('dashboard.upgrade.button', { level: getLevelTranslation(nextUserLevel) })}
                  </Button>
                )}
              </Box>
              
              <Box sx={{ mb: 2 }}>
                <Typography variant="body2" color="text.secondary" gutterBottom>
                  {t('dashboard.progress.completedPatterns')}:
                </Typography>
                <Typography variant="h5" component="div">
                  {completedPatterns.length} / {currentLevelPatterns.length} {t('dashboard.progress.patterns')}
                </Typography>
                <LinearProgress 
                  variant="determinate" 
                  value={currentLevelPatterns.length > 0 ? (completedPatterns.length / currentLevelPatterns.length) * 100 : 0} 
                  sx={{ mt: 1, height: 10, borderRadius: 5 }}
                />
              </Box>
              
              <Box sx={{ display: 'flex', justifyContent: 'space-between', gap: 1 }}>
                <Button 
                  variant="outlined" 
                  color="error" 
                  size="small"
                  startIcon={<RestoreIcon />}
                  onClick={handleResetProgress}
                >
                  {t('dashboard.resetProgress')}
                </Button>
                
                <Button
                  variant="outlined"
                  color="success"
                  size="small"
                  startIcon={<CheckCircle />}
                  onClick={handleCompleteAllPatterns}
                >
                  {t('dashboard.completeAll')}
                </Button>
                
                <Button 
                  variant="outlined" 
                  color="warning" 
                  size="small"
                  onClick={handleResetToBeginnerLevel}
                >
                  {t('dashboard.resetToBeginner')}
                </Button>
              </Box>
            </CardContent>
          </Card>
        </Grid>
        
        {/* 已完成的模式 */}
        <Grid item xs={12} md={6}>
          <Card sx={{ height: '100%' }}>
            <CardContent>
              <Typography variant="h6" gutterBottom>
                {t('dashboard.completed.title')}
              </Typography>
              
              {completedPatterns && completedPatterns.length > 0 ? (
                <List>
                  {completedPatterns.map(pattern => (
                    <ListItem 
                      key={pattern._id}
                      button
                      onClick={() => handlePatternSelect(pattern._id)}
                    >
                      <ListItemIcon>
                        <CompletedIcon color="success" />
                      </ListItemIcon>
                      <ListItemText 
                        primary={pattern.name} 
                        secondary={t(`patterns.categories.${pattern.category.toLowerCase()}.title`)}
                      />
                    </ListItem>
                  ))}
                </List>
              ) : (
                <Box sx={{ py: 2, textAlign: 'center' }}>
                  <Typography variant="body1" color="text.secondary">
                    {t('dashboard.completed.none')}
                  </Typography>
                </Box>
              )}
            </CardContent>
          </Card>
        </Grid>

        {/* 当前等级可用的模式 */}
        <Grid item xs={12}>
          <Card>
            <CardContent>
              <Typography variant="h6" gutterBottom>
                {t('dashboard.available.title')}
              </Typography>

              {currentLevelPatterns && currentLevelPatterns.length > 0 ? (
                <Grid container spacing={3}>
                  {currentLevelPatterns.map(pattern => {
                    const isCompleted = completedPatternsArray.includes(pattern._id);
                    
                    return (
                      <Grid item xs={12} sm={6} md={4} key={pattern._id}>
                        <Card variant="outlined" sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
                          <CardContent sx={{ flexGrow: 1 }}>
                            <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', mb: 1 }}>
                              <Typography variant="h6" component="div">
                                {pattern.name}
                              </Typography>
                              {isCompleted && (
                                <Chip 
                                  label={t('dashboard.completed.title')} 
                                  size="small" 
                                  color="success" 
                                  icon={<CompletedIcon />} 
                                />
                              )}
                            </Box>
                            <Typography variant="body2" color="text.secondary">
                              {pattern.description || t(`patterns.descriptions.${pattern.name}`)}
                            </Typography>
                            <Chip 
                              label={t(`patterns.categories.${pattern.category.toLowerCase()}.title`)}
                              size="small"
                              variant="outlined"
                              sx={{ mt: 1 }}
                            />
                          </CardContent>
                          <CardActions>
                            <Button 
                              size="small" 
                              variant="contained" 
                              color="primary" 
                              fullWidth
                              onClick={() => handlePatternSelect(pattern._id)}
                            >
                              {isCompleted 
                                ? t('dashboard.patternCard.continue') 
                                : t('dashboard.patternCard.startLearning')}
                            </Button>
                          </CardActions>
                        </Card>
                      </Grid>
                    );
                  })}
                </Grid>
              ) : (
                <Box sx={{ py: 2, textAlign: 'center' }}>
                  <Typography variant="body1" color="text.secondary">
                    {t('dashboard.available.none')}
                  </Typography>
                </Box>
              )}
            </CardContent>
          </Card>
        </Grid>
      </Grid>

      {/* 升级对话框 */}
      <Dialog open={upgradeDialogOpen} maxWidth="sm" fullWidth>
        <DialogTitle>
          {t('dashboard.upgrade.modalTitle')}
        </DialogTitle>
        <DialogContent>
          <Box sx={{ py: 2 }}>
            <Typography variant="body1" gutterBottom>
              {generationStatus}
            </Typography>
            <LinearProgress variant="determinate" value={generationProgress} sx={{ mt: 1, mb: 2 }} />
          </Box>
        </DialogContent>
      </Dialog>

      {/* 重置确认对话框 */}
      <Dialog open={resetConfirmOpen} maxWidth="sm" fullWidth>
        <DialogTitle>
          {t('dashboard.resetToBeginner')}
        </DialogTitle>
        <DialogContent>
          <DialogContentText>
            {t('dashboard.confirmResetToBeginner')}
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseResetConfirm}>
            {t('common.cancel')}
          </Button>
          <Button 
            onClick={confirmResetToBeginner} 
            color="error" 
            variant="contained"
          >
            {t('dashboard.resetToBeginner')}
          </Button>
        </DialogActions>
      </Dialog>
    </Container>
  );
};

export default Dashboard;